

class ProjectController extends BaseController{
    def beforeInterceptor = [action:this.auth]
    
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        def access = session.access
        access.refresh()

        def list = access.getList("project");

        Float b = 0;
        for(Project p in list){
            b += p.calcCurrentBalance();
        }

        [ projectInstanceList: list, projectInstanceTotal: list.count(), balance : b ]
    }

    def show = {
        def projectInstance

        // test if transaction started
        if(DBConnection.isConnectionStarted()){
            projectInstance = DBConnection.getProject(params.id)
        }
        else{
            projectInstance = Project.get( params.id )
        }

        if(!projectInstance) {
            flash.message = "Project not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            
            // test if the project is available in current mode
            if(ModeAccess.isAvailableInCurrentMode(session.mode,projectInstance.mode)){
                // If the project mode corresponds to the current mode
                def access = session.access
                access.refresh()
                if(access.checkAccess(session.mode, "project", "show", projectInstance.area.id)){
                    return [
                        projectInstance : projectInstance,
                        numberOfEmployees: projectInstance.getListOfEmployees().size()
                    ]
                }
                else{
                    flash.message = "Missing Authorization!"
                    redirect(action:list)
                }
            }
            else{
                flash.message = "Project not accessible in current mode"
                redirect(action:list)
            }

        }
    }

    def delete = {
        //System.out.println(params.id)
        // test if transaction started
        def projectInstance
        if(DBConnection.isConnectionStarted()){
            projectInstance = DBConnection.getProject(params.id)
        }
        else{
            projectInstance = Project.get( params.id )
        }

        if(projectInstance) {
            def access = session.access
            access.refresh()
            def area = Area.get(projectInstance.area.id)
            if(access.checkAccess(session.mode, "project", "delete", area.container.id)){
                try {
                    projectInstance.delAllEmployees()
                    if(DBConnection.isConnectionStarted()){
                        DBConnection.deleteProject(projectInstance.id)
                    }
                    else{
                        projectInstance.delete(flush:true)
                    }
                    session.modified = true// to show popup window
                    flash.message = "Project ${projectInstance} deleted"
                    redirect(action:list)
                }
                catch(org.springframework.dao.DataIntegrityViolationException e) {
                    flash.message = "Project ${params.id} could not be deleted"
                    redirect(action:show,id:params.id)
                }
            }
            else{
                flash.message = "Missing Authorization!"
                redirect(action:list)
            }
        }
        else {
            flash.message = "Project not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
        //test if transaction started
        def projectInstance
        if(DBConnection.isConnectionStarted()){
            projectInstance = DBConnection.getProject(params.id)
        }
        else{
            projectInstance = Project.get( params.id )
        }

        if(!projectInstance) {
            flash.message = "Project not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            // test if the project can be edited in current mode
            if(ModeAccess.isAvailableInCurrentMode(session.mode,projectInstance.mode)){
                def access = session.access
                access.refresh()
                if(access.checkAccess(session.mode, "project", "edit", projectInstance.area.id)){
                    return [ projectInstance : projectInstance, areas : access.getList("area") ]
                }
                else{
                    flash.message = "Missing Authorization!"
                    redirect(action:list)
                }
            }
            else{
                flash.message = "Project not accessible in current mode"
                redirect(action:list)
            }
        }
    }

    def update = {
        def projectInstance

        //Check that startDate is correct
        if(params.startDate_month.equals("4")||params.startDate_month.equals("6")||params.startDate_month.equals("9")||params.startDate_month.equals("11")){
            if(params.startDate_day.equals("31")){
                    params.startDate_month = "ab"
            }
        }

        if(params.startDate_month.equals("2")){ // check february month
            if(params.startDate_day.equals("31")||params.startDate_day.equals("30")){
                    params.startDate_month = "ab"
            }
        }
        //Check that endDate is correct
        if(params.endDate_month.equals("4")||params.endDate_month.equals("6")||params.endDate_month.equals("9")||params.endDate_month.equals("11")){
            if(params.endDate_day.equals("31")){
                    params.endDate_month = "ab"
            }
        }

        if(params.endDate_month.equals("2")){ // check february month
            if(params.endDate_day.equals("31")||params.endDate_day.equals("30")){
                    params.endDate_month = "ab"
            }
        }
        
        if(DBConnection.isConnectionStarted()){ //connection

            projectInstance = DBConnection.getProject( params.id )
            if(projectInstance) {
                projectInstance.properties = params
                if(!projectInstance.hasErrors()) { //has errors
                    Integer wrong=0
                    // opur constraints
                     if(!projectInstance.activityId){
                        projectInstance.errors.rejectValue("activityId", "project.activityID.is.empty", "The ActivityId should be specified.")
                        wrong=1
                    }

                    if(!projectInstance.activityId.matches("[a-öA-Ö0-9 ]+")){
                        projectInstance.errors.rejectValue("activityId", "project.activityID.mismatch", "The ActivityId contains illegal characters")
                        wrong=1
                    }
                    if(!projectInstance.name.matches("[a-öA-Ö0-9 ]+")){
                        projectInstance.errors.rejectValue("name" ,"project.name.mismatch", "The Name contains illegal characters")
                        wrong=1
                    }
                    if(!projectInstance.name){
                          projectInstance.errors.rejectValue("name" ,"project.name.is.empty", "The Name should be specified.")
                       wrong=1
                    }

                     if(!projectInstance.description){
                        projectInstance.errors.rejectValue("description","project.description.is.empty", "The Description should be specified.")
                         wrong=1
                    }
                    if(projectInstance.startDate>=projectInstance.endDate){
                         projectInstance.errors.rejectValue("startDate" ,"project.startdate.is.empty", "A project's startdate should be")
                         projectInstance.errors.rejectValue("endDate" ,"project.end.is.empty", "before the enddate")
                         wrong=1
                    }
                    if(wrong==1){
                    render(view:'edit',model:[projectInstance:projectInstance] )
                    }
                    else{
                     Integer idP
                   if((idP= DBConnection.updateProject(projectInstance))>0){
                    session.modified = true // to show popup window
                    flash.message = "Project ${projectInstance} updated in sandbox"
                    redirect(action:show,id:projectInstance.id)
                }
                else{
                      //MYSQL
                       if(idP==-2){
                           projectInstance.errors.rejectValue("activityId" ,"project.activityId.is.wrong", "The ActivityId is not unique")
                            render(view:'edit',model:[projectInstance:projectInstance])
                       }
                       if(idP==-3){
                           projectInstance.errors.rejectValue("name" ,"project.name.is.wrong", "The Name is not unique")
                            render(view:'edit',model:[projectInstance:projectInstance])
                       }
               
                }
                    }

            }//has after mysql
                
                else {
                    render(view:'edit',model:[projectInstance:projectInstance])
                }
            }
            else {
                flash.message = "Project not found with id ${params.id}"
                redirect(action:list)
            }
        }//connectionstarted
        else{
            projectInstance = Project.get( params.id )
            if(projectInstance) {
                if(params.version) {
                    def version = params.version.toLong()
                    if(projectInstance.version > version) {

                        projectInstance.errors.rejectValue("version", "project.optimistic.locking.failure", "Another user has updated this Project while you were editing.")
                        render(view:'edit',model:[projectInstance:projectInstance])
                        return
                    }
                }
                projectInstance.properties = params
                if(!projectInstance.hasErrors() && projectInstance.save()) {
                    flash.message = "Project ${projectInstance} updated"
                    redirect(action:show,id:projectInstance.id)
                }
                else {
                    render(view:'edit',model:[projectInstance:projectInstance])
                }
            }
            else {
                flash.message = "Project not found with id ${params.id}"
                redirect(action:list)
            }
        }
    }

    def create = {
        def access = session.access
        access.refresh()
        if(access.checkAccess(session.mode, "project", "create", null)){
            def projectInstance = new Project()
            projectInstance.properties = params
            return ['projectInstance':projectInstance, areas : access.getList("area")]
        }
        else{
            flash.message = "Missing Authorization!"
            redirect(action:list)
        }

    }

    def save = {

        //Check that startDate is correct
        if(params.startDate_month.equals("4")||params.startDate_month.equals("6")||params.startDate_month.equals("9")||params.startDate_month.equals("11")){
            if(params.startDate_day.equals("31")){
                    params.startDate_month = "ab"
            }
        }

        if(params.startDate_month.equals("2")){ // check february month
            if(params.startDate_day.equals("31")||params.startDate_day.equals("30")){
                    params.startDate_month = "ab"
            }
        }
        //Check that endDate is correct
        if(params.endDate_month.equals("4")||params.endDate_month.equals("6")||params.endDate_month.equals("9")||params.endDate_month.equals("11")){
            if(params.endDate_day.equals("31")){
                    params.endDate_month = "ab"
            }
        }

        if(params.endDate_month.equals("2")){ // check february month
            if(params.endDate_day.equals("31")||params.endDate_day.equals("30")){
                    params.endDate_month = "ab"
            }
        }
        
        if(params.mode.equalsIgnoreCase("budget")){
            params.mode=0
        }
        else{
            params.mode=1
        }
        def projectInstance = new Project(params)

        if(!DBConnection.isConnectionStarted()){
            if(projectInstance.currentBudget().variableCosts == null || projectInstance.currentBudget().variableCosts.isEmpty())
            {
                for(CostCategory costCategory : CostCategory.list())
                {
                   projectInstance.currentBudget().addToVariableCosts(amount:(Float)0, category:costCategory )
                }
            }
        }

        def Cid = null
        if(projectInstance.area){
            def area = Area.get(projectInstance.area.id)
             Cid = area.container.id
        }
        
        def access = session.access
        access.refresh()
        if(access.checkAccess(session.mode, "project", "save", Cid)){
            if(!projectInstance.hasErrors()) {//has errors
                if(DBConnection.isConnectionStarted()){ //conection
                    //here check for constraints
                    int wrong=0
                    if(!projectInstance.activityId){
                        projectInstance.errors.rejectValue("activityId", "project.activityID.is.empty", "The ActivityId should be specified.")
                        wrong=1
                    }

                    if(!projectInstance.activityId.matches("[a-öA-Ö0-9 ]+")){
                        projectInstance.errors.rejectValue("activityId", "project.activityID.mismatch", "The ActivityId contains illegal characters")
                        wrong=1
                    }
                    if(!projectInstance.name){
                          projectInstance.errors.rejectValue("name" ,"project.name.is.empty", "The Name should be specified.")
                        wrong=1
                    }

                    if(!projectInstance.name.matches("[a-öA-Ö0-9 ]+")){
                        projectInstance.errors.rejectValue("name" ,"project.name.mismatch", "The Name contains illegal characters")
                        wrong=1
                    }

                     if(!projectInstance.description){
                        projectInstance.errors.rejectValue("description","project.description.is.empty", "The Description should be specified.")
                        wrong=1
                    }
                    if(projectInstance.startDate>=projectInstance.endDate){
                         projectInstance.errors.rejectValue("startDate" ,"project.startdate.is.empty", "A project's startdate should be before the enddate")
                        wrong=1
                    }
                    if(wrong==1){
                        render(view:'create',model:[projectInstance:projectInstance] )
                    }
                    else{
                        Integer idP
                        if((idP=DBConnection.saveProject(projectInstance))>0){
                            session.modified = true// to show popup window
                            flash.message = "Project ${projectInstance} created"
                            for(CostCategory costCategory : CostCategory.list())
                            {
                                projectInstance=DBConnection.getProject(""+idP)
    //                            println("save variable cost???")
                                def budget = projectInstance.currentBudget()
                                DBConnection.saveVariableCost(budget,(Float)0,costCategory )
                            }
                            redirect(action:show,id:idP)
                        }

                        else{
                            //MYSQL
                           if(idP==-2){
                               projectInstance.errors.rejectValue("activityId" ,"project.activityId.is.wrong", "The ActivityId is not unique")
                               render(view:'create',model:[projectInstance:projectInstance])
                           }
                           if(idP==-3){
                               projectInstance.errors.rejectValue("name" ,"project.name.is.wrong", "The Name is not unique")
                               render(view:'create',model:[projectInstance:projectInstance])
                           }
                           else{
                            render(view:'create',model:[projectInstance:projectInstance])
                           }
                        }
                }
                    }
                else{
                    if(projectInstance.save()){
                        flash.message = "Project ${projectInstance} created"
                        redirect(action:show,id:projectInstance.id)
                    }
                    else{
                        render(view:'create',model:[projectInstance:projectInstance])
                    }
                }
                
            }
            else{
                render(view:'create',model:[projectInstance:projectInstance])
            }
        }
        else{
            flash.message = "Missing Authorization!"
            redirect(action:list)
        }
    }

    def add_employee = {
        def p
        if(DBConnection.isConnectionStarted()){
            p = DBConnection.getProject(params.id)
        }
        else{
            p = Project.get(params.id);
        }
        if(p){
            def access = session.access
            access.refresh()
            if(!access.checkAccess(session.mode, "project", "addEmployee", p.area.id)){
                flash.message = "Budget is locked!"
                redirect(action:show, id:params.id)
                return
            }
            ArrayList<Employee> l = new ArrayList<Employee>();
            // test if the project is available in current mode
            if(ModeAccess.isAvailableInCurrentMode(session.mode,p.mode)){
                // Ihe project mode corresponds to the current mode
                
                def employeeList
                employeeList = access.getList("employeeInContainer")
                /*
                if(DBConnection.isConnectionStarted()){
                    employeeList = access.getList("employeeInContainer")
                }
                else{
                    employeeList = Employee.list()
                }
                */
                /* Do not uncomment the line below */
                //employeeList = DBConnection.getEmployeeListByArea(p.area)

                for(Employee e : employeeList){
                    int wantedMode
                    if(session.mode == null || session.mode.equalsIgnoreCase("sandbox")){ // if current mode = sandbox
                       wantedMode=1
                    }
                    else{   // if current mode = budget
                        wantedMode=0
                    }
                    //TODO Modification in order to avoid employee from other container to show up there
                    def pList = p.getListOfEmployees()
                    boolean trouve=false
                    for(Employee emp:pList){
                        if(emp.equals(e)){
                            trouve=true
                            break
                        }
                    }
                    if(!trouve && e.mode==wantedMode){
                        l.add(e);
                    }
                }
                render(view:'add_employee',model:[ employeeList: l, projectid: params.id ])
            }
            else{
                flash.message = "Project not accessible in current mode"
                redirect(action:list)
            }
        }
        else{
            flash.message = "Project not found with id ${params.id}"
            redirect(action:list)
        }

        
    }

    def save_added_employee = {
        String[] vals = request.getParameterValues("employeeid")
        def projectInstance
        if(DBConnection.isConnectionStarted()){
            projectInstance = DBConnection.getProject(params.projectid)
        }
        else{
            projectInstance = Project.get( params.projectid )
        }

        if (projectInstance) {
            def access = session.access
            access.refresh()
            if(!access.checkAccess(session.mode, "project", "addEmployee", projectInstance.area.id)){
                flash.message = "Budget is locked!"
                redirect(action:show, id:params.id)
                return
            }
            for(String v : vals){
                def employee
                if(DBConnection.isConnectionStarted()){
                    employee = DBConnection.getEmployee(v)
                }
                else{
                    employee = Employee.get( v )
                }
                if(employee == null) {
                    System.out.println(v + " fel!");
                }
                else{
                    projectInstance.addEmployee(employee);
                }
            }
           
            if(!DBConnection.isConnectionStarted()){
                if(projectInstance.save(flush:true,validate:false)) {
                    if(vals!=null && vals.length>=1){
                        session.modified = true // to show popup window
                        flash.message = "New employee(s) added"
                    }
                    else{
                        flash.message = "No employee added"
                    }
                }
                else{
                    flash.message = "Cannot add new employee"

                    projectInstance.errors.each {
                        println (it);
                    }
                }
            }
            redirect(action:show, id : params.projectid)
        }
        else{
            flash.message = "Project \"${projectInstance.name}\" not found with id ${params.projectid}"
            redirect(action:list)
        }

    }
    def delete_employee = {
        int wantedMode
        if(session.mode == null || session.mode.equalsIgnoreCase("sandbox")){ // if current mode = sandbox
           wantedMode=1
        }
        else{   // if current mode = budget
            wantedMode=0
        }
        def projectInstance
        if(DBConnection.isConnectionStarted()){
            projectInstance = DBConnection.getProject(params.id)
        }
        else{
            projectInstance = Project.get( params.id )
        }

        if(projectInstance){
            def access = session.access
            access.refresh()
            if(!access.checkAccess(session.mode, "project", "deleteEmployee", projectInstance.area.id)){
                flash.message = "Budget is locked"
                redirect(action:show, id:params.id)
            }
            List<Employee> l = projectInstance.getListOfEmployeesByMode(wantedMode)
            [ employeeList: l, id: params.id ]
        }
        else{
            flash.message = "Project not found with id ${params.id}"
            redirect(action:list)
        }
        
    }

    def save_deleted_employee = {
        String[] del = request.getParameterValues("employeeid")
        def projectInstance
        if(DBConnection.isConnectionStarted()){
            projectInstance = DBConnection.getProject(params.id)
        }
        else{
            projectInstance = Project.get( params.id )
        }
        def access = session.access
        access.refresh()
        if(!access.checkAccess(session.mode, "project", "deleteEmployee", projectInstance.area.id)){
            flash.message = "Budget is locked"
            redirect(action:show, id:params.id)
            return
        }
        for(String x : del){
             // add information about the mode
            def empl
            if(DBConnection.isConnectionStarted()){
                empl = DBConnection.getEmployee(x)
            }
            else{
                empl = Employee.get( x )
            }
            projectInstance.delEmployee(empl)


        }
        if(del!=null && del.length>=1){
            session.modified = true// to show popup window
            flash.message = "Employee(s) deleted from the project"
        }
        else{
            flash.message = "No employee deleted"
        }
        redirect(action:show, id : params.id)
    }

    def updateIncome = {
        Float newIncome = Float.parseFloat(params.figure);

        def projectInstance = DBConnection.getProject(params.id);

        Budget b = projectInstance?.currentBudget();

        if(params.typeOfIncome == "expectedIncome"){
            b.expectedTotalIncome = newIncome;
        }
        else if(params.typeOfIncome == "knownIncome"){
            b.knownTotalIncome = newIncome;
        }
        
        if(DBConnection.isConnectionStarted()){
            if(newIncome<0){
                  flash.message = "Cost should be positive"
                    redirect(action:blank);
                    }
            if(DBConnection.updateBudget(b)>0){
                session.modified = true // to show popup window
            }
            else{
                 projectInstance.errors.each {
                      println(it);
                    }
                    b.errors.each {
                     println(it);
                    }
            }
        }
        else{
            if(projectInstance.save(flush:true)){

            }
            else{
                 projectInstance.errors.each {
                      println(it);
                    }
                    b.errors.each {
                     println(it);
                    }
            }
        }

         render(view:'show',model:[ projectInstance: projectInstance ])
        
    }

    def updateVariableCost =
    {
        Float newCost = Float.parseFloat(params.figure);
        def projectInstance = DBConnection.getProject(params.id);
        Budget b = projectInstance?.currentBudget();

        if(!params.idVariableCost.startsWith("variableCost_"))
        {
            flash.message = "Incorrect variable_cost_id"
            redirect(action:blank);
        }
         

        int vId= (int)Integer.parseInt(params.idVariableCost.replace("variableCost_",""))
        VariableCost cost = null
        
        if(DBConnection.isConnectionStarted()){
            for(VariableCost vCost: DBConnection.getVariableCostList(b))
            {
                if(newCost<0){
                  flash.message = "Cost should be positive"
                    redirect(action:blank);
                    }
                if(vCost.id == vId)
                {
                    cost=vCost
                    break
                }
            }
        }
        else{
            for(VariableCost vCost: b.variableCosts)
            {
                if(vCost.id == vId)
                {
                    cost=vCost
                    break
                }
            }
        }
        

        if(cost == null)
        {
            flash.message = "Tried to edit a nonexistant cost"
            redirect(action:blank);
        }

        cost.amount = newCost

        if(DBConnection.isConnectionStarted()){
            if(DBConnection.updateVariableCost(cost)>0){
                session.modified = true // to show popup window
            }
            else{
                 projectInstance.errors.each {
                      println(it);
                    }
                    b.errors.each {
                     println(it);
                    }
            }
        }
        else{
            if(projectInstance.save(flush:true)){

            }
            else{
                 projectInstance.errors.each {
                      println(it);
                    }
                    b.errors.each {
                     println(it);
                    }
            }
        }
        redirect(action:blank);
    }

    def changeMode = {
        //System.out.println("-"+session.mode+"-")
        if((session.mode==null)||(!session.mode.equalsIgnoreCase("budget"))){
              session.mode="budget"
              DBConnection.rollbackTransaction()
        }
        else{
            session.mode="sandbox"
            DBConnection.connect()
            DBConnection.startTransaction()

        }
        //System.out.println("-"+session.mode+"-")

        flash.message = "Mode changed"
        if(params.idProject.equals("null")){
            redirect(controller:params.currentController,action:params.currentView)
        }
        else{
            redirect(controller:params.currentController,action:params.currentView, id:params.idProject)
        }
    }
    
    def updateExpenditure = {
        Float f = Float.parseFloat(params.figure);

        def projectInstance = DBConnection.getProject(params.id);

        Budget b = projectInstance?.currentBudget();

        if(params.type == "knownExpenditure"){
            b.knownVariableCost = f;
        }

        if(DBConnection.isConnectionStarted()){
             if(f<0){
                  flash.message = "Cost should be positive"
                    redirect(action:blank);
                    }
            if(DBConnection.updateBudget(b)>0){
                session.modified = true // to show popup window

            }
            else{
                 projectInstance.errors.each {
                      println(it);
                    }
                    b.errors.each {
                     println(it);
                    }
            }
        }
        else{
            if(projectInstance.save(flush:true)){

            }
            else{
                 projectInstance.errors.each {
                      println(it);
                    }
                    b.errors.each {
                     println(it);
                    }
            }
        }

        redirect(action:blank);

    }

    def blank = {}

    def updateHours = {
        Double f = Double.parseDouble(params.figure);
        Float x = 0;

        Whoa w = Whoa.get(params.whoaId);
        println("Timmar: "+ w.hours)
        // Float newFigure = Float.parseFloat(params.figure);

        def employeeInstance

        if(params.type == "updateHours"){
            
            w.hours = f;
        }
        else{
            if (session.mode.equalsIgnoreCase('budget')) {
                employeeInstance = Employee.get((int)w.member.id);
            }
            else {
                employeeInstance = DBConnection.getEmployee(w.member.id.toString())
            }
            if (params.type == "updateProjectPercentage") {
                w.hours = (f/100)*employeeInstance.hoursForAge();
            }
            else if (params.type == "percentageWorkUpArrowProject") {
                x = (w.hours/employeeInstance.hoursForAge())+0.01;
                w.hours = x*employeeInstance.hoursForAge();
            }
            else if (params.type == "percentageWorkDownArrowProject") {
                x = (w.hours/employeeInstance.hoursForAge())-0.01;
                w.hours = x*employeeInstance.hoursForAge();
            }
            else if (params.type == "percentageWorkUpArrowCourse") {
                x = (employeeInstance.actualWorkingHoursCourse()/employeeInstance.hoursForAge())+0.01;
                w.hours = x*employeeInstance.hoursForAge();
            }
            else if (params.type == "percentageWorkDownArrowCourse") {
                x = (employeeInstance.actualWorkingHoursCourse()/employeeInstance.hoursForAge())-0.01;
                w.hours = x*employeeInstance.hoursForAge();
            }

        }

        if(DBConnection.isConnectionStarted()){
            if(DBConnection.updateWhoa(w)>0){
                session.modified = true // to show popup window
            }
            else{
            }
        }
        else{
            if(w.save(flush:true)){

            }
            else{

            }
        }
        
        redirect(action:blank);
         //render(view:'show',model:[ projectInstance: projectInstance ])

    }
    
}
